package com.service;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Timer;
import java.util.TimerTask;

@Component
public class MQListener {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RabbitListener(queues = "s2020_1_3_queue")
    @RabbitHandler
    public void recv(Message msg, Channel channel) {
        long[] t = new long[]{1000 * 10, 1000 * 60, 1000 * 60 * 30, 1000 * 60 * 60, 1000 * 60 * 60 * 6, 1000 * 60 * 60 * 8, 1000 * 60 * 60 * 10, 1000 * 60 * 60 * 15, 1000 * 60 * 60 * 20, 1000 * 60 * 60 * 24};
        String uuid = msg.getMessageProperties().getMessageId();
        try {
            int n = 1 / 0;
            //确认已经正确处理好消息了，消息在队列里面编号，是否一性处理所有比当前编号小的消息
            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // e.printStackTrace();
            try {
                //消息编号，是否重发,这个最好不要使用，会死循环，且每次重发处理还是这条
                //channel.basicReject(msg.getMessageProperties().getDeliveryTag(),true);


                Integer count = (Integer) redisTemplate.boundValueOps(uuid).get();
                if (count == null) {
                    count = 0;
                }
                count++;
                redisTemplate.boundValueOps(uuid).set(count);
                if (count < 10) {
                    //丢弃消息: 消息编号，是否批量，是否重发,一般不用true,重试次要自己处理好
                    channel.basicNack(msg.getMessageProperties().getDeliveryTag(), false, false);

                    //定时重发消息,这种方式会排队
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            rabbitTemplate.convertAndSend(msg.getMessageProperties().getReceivedExchange(), msg.getMessageProperties().getReceivedRoutingKey(), msg);
                        }
                    }, t[count - 1]);

                } else {
                    //进一步处理
                }


            } catch (Exception ex) {
                //  ex.printStackTrace();;

            }

        }
        String str = new String(msg.getBody());
        System.out.println("收到消息了:" + str);
    }

}
